from django.core.management.base import NoArgsCommand
from django.conf import settings
from app.luca_customer.models import *
from datetime import date
import csv
settings.USE_TZ = False

class Command(NoArgsCommand):
    def handle(self, *args, **options):
        with open(settings.VAR_DIR+"import/customer.csv") as customers:
            reader = csv.reader(customers)
            count=0
            for customer in reader:
                name = customer[3].strip()
                telephone = customer[4].strip()
                group = customer[1].strip()
                location = customer[2].strip()

        
                if Customer.objects.filter(telephone=telephone).exists():
                    print "_Error: "+telephone+" is exists"
                    continue
        
                if not Group.objects.filter(name=group).exists():
                    group_data = Group(name=group,active=1,created_at=date.today(),updated_at=date.today())
                    group_data.save() 
                    
                group_id = Group.objects.get(name=group).id
                
                if not Location.objects.filter(name=location).exists():
                    location_data = Location(name=location,active=1,created_at=date.today(),updated_at=date.today())
                    location_data.save() 
                    
                location_id= Location.objects.get(name=location).id
                
                
                
                customer_data = Customer(name=name, group_id=group_id, telephone=telephone,location_id=location_id,active=1,created_at=date.today(),updated_at=date.today())
                customer_data.save() 
                
                count+=1
                print "_"+str(count),telephone,"was imported"